package com.wondertek.poms.service.message;


import cn.hutool.core.date.DateUtil;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.core.service.IChannelPackageService;
import com.wondertek.poms.core.service.IEquityTreeAbilityLogService;
import com.wondertek.poms.core.service.IEquityTreeMQLogService;
import com.wondertek.poms.core.service.IEquityTreeService;
import com.wondertek.poms.core.service.IProductGroupService;
import com.wondertek.poms.core.service.ISystemConfigService;
import com.wondertek.poms.core.utils.FileIo;
import com.wondertek.poms.dao.po.EquityTreeMQLog;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Slf4j
@Component
public class SendAbility{

    @Autowired
    private ISystemConfigService systemConfigService;
    @Autowired
    private IProductGroupService productGroupService;
    @Autowired
    private IEquityTreeMQLogService equityTreeMQLogService;
    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private IEquityTreeAbilityLogService equityTreeAbilityLogService;
    @Autowired
    private IEquityTreeService equityTreeService;
    @Autowired
    private IChannelPackageService channelPackageService;

    /**
     * 产品组，权益树的发布和撤回
     * @param id   groupId,equityTreeId
     * @param oprCode   1:发布   0：撤回
     * @param name   groupName,equityTreeName
     * @param type  1:权益树 2:产品组 3:产品包 4:渠道包
     * @return
     */
    public Boolean sendToAbility(Long id, Integer oprCode, String name, String type){
        String xmlName= "";
        Map<String, Object> map = new HashMap<>();
        if(oprCode == 1){
            switch(type){
                case "1":
                    map= equityTreeService.getEquityTreeMap(id);
                    break;
                case "2":
                    map = productGroupService.getProductGroupMap(id);
                    break;
                case "4":
                    map = channelPackageService.getChannelPackageMap();
                    break;
            }
            xmlName= getXmlName(map, name, type);
        }
        return publishToAbility(id,oprCode,name,type,xmlName);
    }


    /**
     * 产品组，权益树的发布和撤回
     * @param id   groupId,equityTreeId
     * @param oprCode   1:发布 2：撤回  3：删除
     * @param name   groupName,equityTreeName
     * @param type  1:权益树 2:产品组 3:产品包 4:渠道包
     * @return
     */
    public Boolean publishToAbility(Long id, Integer oprCode, String name, String type, String xmlName) {
        Boolean publishFlag=false;
        if(type.equals("4")){
            xmlName="channelPkgs";
        }
        String pushRelationIds = systemConfigService.findAllBykey("EQUITY_TREE_QUEUES").getValue();
        if(!StringUtil.isNullStr(pushRelationIds)){
            String[] arrayPushRelationId = pushRelationIds.split(",");
            for(String pushRelationId : arrayPushRelationId){
                EquityTreeMQLog equityTreeMQLog = equityTreeMQLogService.save(new EquityTreeMQLog(id, name, xmlName, type,oprCode,StringUtil.nullToLong(pushRelationId)));
                try {
                    log.info("发送能力平台流程|发布信息："+equityTreeMQLog);
                    log.info("发送能力平台流程|发布队列："+ Constants.QUEUE_PRDINFO_PUBLISH + pushRelationId);
                    jmsTemplate.convertAndSend(Constants.QUEUE_PRDINFO_PUBLISH + pushRelationId, equityTreeMQLog);
                    log.info("发送能力平台流程|发布成功");
                    equityTreeMQLog.setStatus(12);
                    publishFlag = true;
                } catch (Exception e) {
                    log.info("发送能力平台流程|发布失败："+e);
                    equityTreeMQLog.setStatus(13);
                }
                equityTreeMQLogService.save(equityTreeMQLog);
            }
        }

        /*EquityTreeAbilityLog equityTreeAbilityLog = new EquityTreeAbilityLog(id, name, xmlName, type,oprCode,0l);
        equityTreeAbilityLogService.save(equityTreeAbilityLog);;
        try {
            String abilityOn = systemConfigService.findAllBykey("PUBLISH_ABILITY_SWITCH").getValue();
            if (abilityOn == null || !abilityOn.equals("on")) {
                log.info("==推送能力平台开关未配置或者已关闭==");
                return publishFlag;
            }
            String url =systemConfigService.findAllBykey("PUBLISH_ABILITY_URL_EQUITY").getValue();
            if(StringUtil.isNullStr(url)){
                log.info("====推送能力平台接口URL[PUBLISH_ABILITY_URL_EQUITY]未配置======");
                return publishFlag;
            }

            AbilityEquityReturnVo abilityEquityReturnVo=new AbilityEquityReturnVo();
            abilityEquityReturnVo.setId(String.valueOf(equityTreeAbilityLog.getId()));
            abilityEquityReturnVo.setType(String.valueOf(equityTreeAbilityLog.getType()));
            abilityEquityReturnVo.setPushContentId(String.valueOf(equityTreeAbilityLog.getPushContentId()));
            abilityEquityReturnVo.setXmlName(String.valueOf(equityTreeAbilityLog.getXmlName()));
            abilityEquityReturnVo.setOprTime(DateUtil.format(equityTreeAbilityLog.getOprTime(),"yyyyMMddHHmmss"));
            abilityEquityReturnVo.setOprCode(String.valueOf(equityTreeAbilityLog.getOprCode()));
            boolean flag = HttpUtils.doPost(url, abilityEquityReturnVo ,"code" ,"0");
            if (flag) {
                equityTreeAbilityLog.setStatus(12);
                log.info("推送消息["+equityTreeAbilityLog.getId()+"]" + equityTreeAbilityLog.getPushContentId() + "结果成功!");
                publishFlag=true;
            } else {
                equityTreeAbilityLog.setStatus(13);
                log.info("推送消息["+equityTreeAbilityLog.getId()+"]" + equityTreeAbilityLog.getPushContentId() + "结果失败!");
            }
        } catch (Exception e) {
            equityTreeAbilityLog.setStatus(13);
            log.info("推送消息["+equityTreeAbilityLog.getId()+"]" + equityTreeAbilityLog.getPushContentId() + "结果失败!");
        }
        equityTreeAbilityLogService.save(equityTreeAbilityLog);*/
        return publishFlag;
    }


    private String getXmlName(Map<String, Object> map, String name, String type){

        String cpath =  name +"_"+ DateUtil.format(new Date(),"yyyyMMddHHmmss") + ".xml";
        String basePath="";
        if("1".equals(type) | "2".equals(type)){
            basePath = systemConfigService.findAllBykey("PRICE_MQ_XML_BASE_PATH").getValue();
            if(StringUtil.isNullStr(basePath)) {
                basePath = "/nas/bak_poms3/cmvideo,/poms_publish/cmvideo,/poms_publish_end/cmvideo";
            }
        }else if("4".equals(type)){
            basePath = systemConfigService.findAllBykey("PUBLISH_CHANNEL_BASE_PATH").getValue();
            if(basePath == null || basePath.equals("")) {
                log.error("====发布渠道包信息nas地址PUBLISH_CHANNEL_BASE_PATH未配置====");
                return "";
            }
        }

        String[] dp = basePath.split(",");;

        /**合成xml*/
        StringBuffer resultXml = new StringBuffer();
        String tmpPath = "";
        if("1".equals(type)){
            tmpPath = dp[0] +"/equityTree/" +  cpath;
        }else if("2".equals(type)){
            tmpPath = dp[0] + "/productGrop/" + cpath;//临时地址暂时未定*/
        }else if("4".equals(type)){
            tmpPath = "" + File.separator + "publish"
                    + File.separator + Math.round((Math.random()*1000)) + "-" + new Date().getTime() + ".xml";
        }
        log.info("发送能力平台|合成xml路径："+tmpPath);

        Configuration cfg = new Configuration();
        cfg.setDefaultEncoding("utf-8");
        cfg.setEncoding(Locale.getDefault(), "utf-8");
        cfg.setStrictSyntaxMode(true);
        cfg.setNumberFormat("0");
        cfg.setClassForTemplateLoading(SendAbility.class, "/");
        File localFile = new File(tmpPath);
        if (!localFile.getParentFile().exists()) {
            localFile.getParentFile().mkdirs();
        }
        OutputStreamWriter out = null;
        Template template;
        try {
            out = new OutputStreamWriter(new FileOutputStream(localFile), "UTF-8");
            if("1".equals(type)){
                template = cfg.getTemplate("/template/equityTree.ftl");
                template.process(map, out);
            }else if("2".equals(type)){
                template = cfg.getTemplate("/template/productGroup.ftl");
                template.process(map, out);
            }else if("4".equals(type)){
                template = cfg.getTemplate("/template/vomsChannelPublish.ftl");
                template.process(map, out);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }finally{
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //resultXml.append(FileUtil.loadAFileToString(new File(tmpPath)));
        File tmp = new File(tmpPath);
	    /*if(tmp.exists()) {
			tmp.delete();
		}*/
        for(String p : dp) {
            if(dp[0].equals(p)){
                continue;
            }
            if(!StringUtil.isNullStr(p)) {
                if("1".equals(type)){
                    FileIo.fileCopy(tmpPath, p + "/equityTree/" + cpath, true);
                    File file = new File(p + "/equityTree/" + cpath);
                    if(!file.exists()){
                        log.info("====权益树:"+name+"推送时"+"存储:"+p+"无法访问");
                    }
                }else if("2".equals(type)){
                    FileIo.fileCopy(tmpPath, p + "/productGrop/" +  cpath, true);
                    File file = new File(p + "/productGrop/" +  cpath);
                    if(!file.exists()){
                        log.info("====产品组:"+name+"推送时"+"存储:"+p+"无法访问");
                    }
                }else if("4".equals(type)){
                    String path = p + File.separator+ "channelpak.xml";
                    FileIo.fileCopy(tmpPath, path, true);
                }
            }
        }

        return cpath;

    }
}
